package com.kaishengit.web;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;


import com.kaishengit.entity.MyFile;
import com.kaishengit.entity.Files;
import com.kaishengit.entity.User;
import com.kaishengit.service.FileService;
import com.kaishengit.service.MessageService;
import com.kaishengit.util.PKutil;
import com.kaishengit.util.Page;
public class FileServlet extends HttpServlet {
	private FileService service = new FileService();
	private MessageService ms = new MessageService();

	private static final long serialVersionUID = 1L;
	private static Map<String,String> map = new HashMap<String, String>();
	static{
		map.put(".pdf", "application/pdf");
		map.put(".jpg", "image/jpeg");
		map.put(".png", "image/png");
		map.put(".gif", "image/gif");
		map.put(".mp3","audio/mp3");
		map.put(".word", "applicetion/msword");
		map.put(".zip", "application/octet-stream");
		map.put(".doc", "msword");
	}
	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		String  method = request.getParameter("method");
		if(method == null || "".equals(method)){
			tofile(request,response);
		}else if("createFiles".equals(method)){
			String httpMethod  = request.getMethod();
			if("POST".equals(httpMethod)){
				createFiles(request,response);
			}
		}else if("toSingleFile".equals(method)){
			toSingleFile(request,response);
		}else if("toDownload".equals(method)){
			toDownload(request,response);
		}else if("newFile".equals(method)){
			String httpMethod  = request.getMethod();
			if("POST".equals(httpMethod)){
				uploadFile(request,response);
			}else if("GET".equals(httpMethod)){
				toNewFile(request,response);
			}
			
		}else if("del".equals(method)){
			todel(request,response);	
		}else if("editName".equals(method)){
			toEditName(request,response);
			
		}else if("delFiles".equals(method)) {
			todelFiles(request,response);
		}else{
			response.sendError(404);
			
		}
	}
	private void todelFiles(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		String id = request.getParameter("id");
		String p = request.getParameter("p");
		service.delFiles(id);
		int pageNum = 0;
		if(p==null){
			 pageNum=1; 
		}else{
			pageNum = Integer.valueOf(p);
			
		}
		response.sendRedirect("file.jspx?p="+pageNum);
		
		
	}
	private void toEditName(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		String id = request.getParameter("id");
		String p = request.getParameter("p");
		int pageNum = 0;
		if(p==null){
			 pageNum=1; 
		}else{
			pageNum = Integer.valueOf(p);
			
		}
		String name = request.getParameter("name");
		String v = new String(name.getBytes("Iso8859-1"),"utf-8");
		Files files = service.findFilesById(id);
		service.editName(id,v,files);
		response.sendRedirect("file.jspx?p="+pageNum);
		
	}
	private void todel(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String id = request.getParameter("id");
		ms.delByFileId(id);
		service.del(id);
		HttpSession session = request.getSession();
		Files files =  (Files) session.getAttribute("singleFilesId");
		response.sendRedirect("file.jspx?method=toSingleFile&id="+files.getId());
		
	}
	private void uploadFile(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		HttpSession session = request.getSession();
		User user = (User) session.getAttribute("user");
		String projectid=(String) session.getAttribute("projectid");
		String filesId = request.getParameter("id");
		MyFile file = new MyFile();
		file.setFilesId(filesId);
		File uploadfile = new File("c:/upload");
		File temp = new File("c:/temp");
		if(!uploadfile.exists()){
			uploadfile.mkdir();
		}
		if(!temp.exists()){
			temp.mkdir();
		}
		if(ServletFileUpload.isMultipartContent(request)){
			DiskFileItemFactory  factory = new DiskFileItemFactory();
			factory.setSizeThreshold(1024*10);
			factory.setRepository(temp);
			ServletFileUpload fileUpload  = new ServletFileUpload(factory);
			fileUpload.setFileSizeMax(1024*1024*20);
			try {
				List<FileItem> list = fileUpload.parseRequest(request);
				for(FileItem item:list){
					if(item.isFormField()){
						String value = item.getString();
						if(value == null){
							
						}else{
							String v = new String(value.getBytes("Iso8859-1"),"utf-8");
							file.setName(v);
						}
							
					}else{
						String name = item.getName();
						if(file.getName() != null){
							String fname = file.getName().concat((name.substring(name.lastIndexOf("."))));
							file.setName(fname);
						}else{
							file.setName(name);
						}
						int size = (int)item.getSize();
						file.setSize(size);
						InputStream stream = item.getInputStream();
						String md5 = DigestUtils.md5Hex(stream);
						File f = check(md5);
						if(f == null){
							InputStream stream2 = item.getInputStream();
							byte[] buffer = new byte[1024];
							String filename = PKutil.getPk();
							filename = filename.concat(name.substring(name.lastIndexOf(".")));
							file.setFileName(filename);
							int len = -1;
							OutputStream os = new FileOutputStream(new File(uploadfile,filename));
							while((len = stream2.read(buffer))!=-1){
								os.write(buffer,0,len);
							}
							os.flush();
							os.close();
							stream.close();
						}else{
							String fileName1 = f.getName();
							System.out.println(fileName1+"**********************");
							file.setFileName(fileName1);
						}
						file.setId(PKutil.getPk());
						file.setUserId(user.getId());
						service.save(file,projectid);
						response.sendRedirect("file.jspx?method=newFile&code=1002");
					}
					
					
				}
			} catch (FileUploadException e) {
				e.printStackTrace();
			}
			
		}
		
	}
	public File check(String md5) throws IOException{
		File file = new File("c:/upload");
		File[] fileList = file.listFiles();
		if(fileList.length !=0){
			for(File f:fileList){
				InputStream is = new FileInputStream(new File(file,f.getName()));
				String md51 = DigestUtils.md5Hex(is);
				if(md51.equals(md5)){
					return f; 
				}
			}
			return null;
		}else{
			return null;
		}
		
	}
	private void toNewFile(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		request.getRequestDispatcher("WEB-INF/views/new_file.jsp").forward(request, response);
		
	}
	private void toDownload(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		String trueName = request.getParameter("name");
		String extName = trueName.substring(trueName.lastIndexOf("."));
		File file = new File("c:/upload",trueName);
		if(!file.exists()){
			response.sendError(404,"文件不存在");
		}else {
			MyFile myfile = service.findFileByTrueName(trueName);
			String encodedfileName = new String(myfile.getName().getBytes("UTF-8"),"ISO8859-1");
			response.setHeader("Content-Disposition", "attachment; filename=\"" + encodedfileName + "\""); 
			response.setContentType(map.get(extName));
			response.setContentLength((int) file.length());
			FileInputStream fs = new FileInputStream(file);
			OutputStream os = new FileOutputStream(file);
			byte[] buffer = new byte[512];
			int len = -1;
			while((len = fs.read(buffer))!= -1){
				os.write(buffer,0,len);
			}
			os.flush();
			os.close();
			fs.close();
		}
		
		
	}
	private void toSingleFile(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String id = request.getParameter("id");
		String p = request.getParameter("p");
		Files files = service.findFilesById(id);
		if(files!=null){
			Page<MyFile> page = service.findAllFileByFilesId(id,p);
			request.setAttribute("fileList", page);
			HttpSession session = request.getSession();
			session.setAttribute("singleFilesId", files);
			request.getRequestDispatcher("WEB-INF/views/singlefile.jsp").forward(request, response);
			return;
		}
		response.sendError(404,"此资源不存在！");
		
		
		
	}
	/**
	 * 将创建的文件夹 存到数据库中
	 * @param request
	 * @param response
	 * @throws IOException 
	 * @throws ServletException 
	 */
	private void createFiles(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String name = request.getParameter("name");
		String v = new String(name.getBytes("Iso8859-1"),"utf-8");
		HttpSession session = request.getSession();
		User user = (User) session.getAttribute("user");
		String id = (String) session.getAttribute("projectid");
		service.saveFiles(v,user,id);
		response.sendRedirect("file.jspx");
		
	}
	/**
	 * 根据用户所参与的项目查找到所有的相关文件夹，并跳转到 file.jsp页面进行显示
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void tofile(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String p = request.getParameter("p");
		HttpSession session = request.getSession();
		String id =(String) session.getAttribute("projectid");
		Page<Files> list =  service.findAllFiles(id,p);
		request.setAttribute("filesList", list);
		request.getRequestDispatcher("WEB-INF/views/file.jsp").forward(request, response);
		
	}
	
}
